# coding=utf-8
import re
import feedparser
import pymongo
from bson import json_util
from flask import Flask
from flask.ext.restful import Api, Resource, marshal
from flask.ext.restful import fields
import json
import socket

from Models import CategoryModel, ResultModel, MusicModel, ArticleModel, ImageModel

app = Flask(__name__)
api = Api(app)

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
REFERRER = 'http://www.baidu.com'

socket.setdefaulttimeout(2.0)

conn = pymongo.MongoClient('localhost', 27017, connect=False)

db = conn['Prometheus']
collec_music = db['musics']
collec_rss = db['rss']


@app.route('/')
@app.route('/<page>')
def index(page=1):
    return 'hello'


# @app.route('/category/<int:page>')
# def category(page=0):
#     rsss = collec_rss.find({}).sort('usersCount', -1).skip(page*20).limit(20)
#     data = []
#     for i in rsss:
#         md = CategoryModel()
#         md.id = i.get('_id')
#         md.src = i.get('title')
#         md.logo =i.get('avatar')
#         md.des =i.get('description')
#         md.usersCount = i.get('usersCount')
#         data.append(md)
#     return out_format(True, u'成功', data)


@app.route('/musics/<int:page>')
def musics(page=0):
    data = collec_music.find({}).sort('_id', 1).skip(page*100).limit(100)
    json_results = []
    for i in range(0, 100, 10):
        json_results.append(data[i])
    musicModel = MusicModel()
    musicModel.result = True
    musicModel.message = u'成功'
    musicModel.data = json_results
    # return json.dumps(musicModel, default=lambda obj: obj.__dict__)
    return json.dumps(musicModel.__dict__, default=json_util.default)


ErrorOffset = 0


@app.route('/articles/<int:page>')
def article(page=0, ErrorOffset=ErrorOffset):
    rsss = collec_rss.find({'type': 'rss'}).sort('usersCount', -1)
    # rsss = rss.find({})
    while True:
        ot = rsss[page + ErrorOffset]
        title = ot.get('title')
        avatar = ""
        avatar = ot.get('avatar', '')
        url = ot.get('url')
        # if hasattr(ssl, '_create_unverified_context'):
        #     ssl._create_default_https_context = ssl._create_unverified_context
        feed = feedparser.parse(url, agent=USER_AGENT, referrer=REFERRER)
        if len(feed.entries) != 0:
            break
        else:
            ErrorOffset += 1

    entries = feed.entries
    data = []
    for entry in entries:
        atc = ArticleModel()
        atc.src = title
        atc.logo = avatar
        atc.title = entry.title
        keys = entry.keys()
        if 'content' in keys:
            atc.des = entry.content[0].value
        else:
            atc.des = entry.summary
        atc.image = getImg(atc.des)
        atc.date = entry.published
        atc.type = 0
        data.append(atc)
    return out_format(True, u'成功', data)


@app.route('/images/')
def images():
    feed = feedparser.parse('https://500px.com/upcoming.rss')
    entries = feed.entries
    data = []
    for entry in entries:
        img = ImageModel()
        img.src = '500 px'
        img.logo = 'http://image.coolapk.com/apk_logo/2015/1214/257251_1450078566_192.png'
        keys = entry.keys()
        if 'content' in keys:
            img.image = getImg2(entry.content[0].value)
        else:
            img.image = getImg2(entry.summary)
        img.date = entry.published
        img.type = 1
        data.append(img)
    return out_format(True, u'成功', data)


def getImg(html):
    line = html
    matchObj = re.search('<img[\\w\\W]*?src=[\'|\']?([\\w\\W]*?)(jpg|png|gif|bmp|jpeg)[\\w\\W]*?/>', line, re.M | re.I)

    if matchObj:
        return matchObj.group(1) + matchObj.group(2)
    else:
        return ""


def getImg2(html):
    line = html
    matchObj = re.search("<img[^>]*src=[\"']*([^>\"']+)[\"']*\\s*/>", line, re.M | re.I)
    if matchObj:
        return matchObj.group(1)
    else:
        return ''


def out_format(result=None, message=None, data=None):
    out = ResultModel()
    out.result = result
    out.message = message
    out.data = data
    return json.dumps(out, default=lambda obj: obj.__dict__)

# class MusicList(Resource):
#     def get(self):
#         return True
#
#     def post(self):
#         return True
# api.add_resource(MusicList, '/musics')

# parser = reqparse.RequestParser()
# parser.add_argument('task', type=str)


# class CategoryItem(Resource):
#     def get(self, cat_id):
#         rsss = collec_rss.find_one({'_id': cat_id})
#         return rsss
#
#     def post(self, cat_id):
#         # args = parser.parse_args()
#         # data = args['data']
#         # collec_rss.insert(data)
#         return ""
#
#     def put(self, cat_id):
#         collec_rss.update({'_id': cat_id}, {"$set": {"status": "", "postsPerDay": "", "usersCount": ""}})
#         return ""
#
#     def delete(self, cat_id):
#         collec_rss.remove({'_id': cat_id})
#         return ""

cat_fields = {
    'id': fields.String,
    'src': fields.String,
    'logo': fields.String,
    'des': fields.String,
    'usersCount': fields.Integer,
}


class CategoryList(Resource):
    def get(self, page):
        rsss = collec_rss.find({}).sort('usersCount', -1).skip(page*20).limit(20)
        data = []
        for i in rsss:
            md = CategoryModel()
            md.id = i.get('_id')
            md.src = i.get('title')
            md.logo = i.get('avatar')
            md.des = i.get('description')
            md.usersCount = i.get('usersCount')
            data.append(md)
        # out_format(True, u'成功', data)
        # return marshal(data[0], cat_fields)
        return {'result': True, 'message': '成功', 'data': [marshal(item, cat_fields) for item in data]}

api.add_resource(CategoryList, '/category/<int:page>')
# api.add_resource(CategoryItem, '/categoryitem/<cat_id>')

if __name__ == '__main__':

    app.run()
